<template>
	<view class="discover-container">
		<!-- 顶部导航栏 - 与 index 保持一致 -->
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="title">发现</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-input-box">
				<text class="icon-search">🔍</text>
				<input type="text" class="search-input" placeholder="搜索智能体" placeholder-class="search-placeholder"
					v-model="searchKey" @confirm="handleSearch" />
			</view>
		</view>

		<!-- 标签栏 -->
		<scroll-view scroll-x class="tag-scroll" :show-scrollbar="false">
			<view v-for="(tag, index) in tags" :key="index" :class="['tag-item', currentTag === index ? 'active' : '']"
				@tap="switchTag(index)">
				{{ tag }}
			</view>
		</scroll-view>

		<!-- banner区域 -->
		<view class="banner-box" @tap="handleBannerTap">
			<image src="" mode="aspectFill" class="banner-img" />
			<view class="banner-text">智能锁AI客服</view>
			<view class="banner-btn">快来试试吧</view>
		</view>

		<!-- AI列表 -->
		<scroll-view scroll-y class="device-list" @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="refreshing" @refresherrefresh="refresh">
			<view class="device-item" v-for="item in deviceList" :key="item.id">
				<image class="avatar" :src="item.icon || defaultAvatar" mode="aspectFill" />
				<view class="content">
					<view class="title">{{ item.name }}</view>
					<view class="desc">{{ item.description }}</view>
					<view class="chat-info">
						<view class="chat-count">{{ formatNumber(item.chatCount) }}万人聊过 · @{{ item.creatorName }}</view>
					</view>
				</view>
				<view class="add-btn" @tap.stop="handleAdd(item)">+</view>
			</view>
		</scroll-view>

		<!-- 底部导航栏 - 与 index 保持一致 -->
		<view class="tab-bar">
			<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
				@tap="switchTab(index)">
				<text class="iconfont" :class="tab.icon" />
				<text class="text">{{ tab.text }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref,onMounted } from 'vue'
	import { useDeviceStore } from '@/stores'
	import { message } from '@/utils'
	import { system } from '@/utils/system'
	
	const deviceStore = useDeviceStore()
	const statusBarHeight = system.getStatusBarHeight()

	// 默认头像
	const defaultAvatar = '/static/images/default-avatar.png'

	// 搜索相关
	const searchKey = ref('')
	const originalList = ref([]) // 保存原始数据
	// 搜索处理
	const handleSearch = () => {
		const keyword = searchKey.value.trim().toLowerCase()
		if (!keyword) {
			deviceList.value = originalList.value // 搜索词为空时显示所有数据
			return
		}

		// 前端实现模糊搜索
		deviceList.value = originalList.value.filter(item =>
			item.name.toLowerCase().includes(keyword) ||
			item.description.toLowerCase().includes(keyword)
		)
	}

	// 标签配置 
	const tags = ['推荐']
	const currentTag = ref(0)


	// 底部导航配置
	const tabs = [{
			text: '对话',
			icon: 'icon-message'
		},
		{
			text: '发现',
			icon: 'icon-search'
		},
		{
			text: '创建',
			icon: 'icon-add'
		},
		{
			text: '通知',
			icon: 'icon-notification'
		},
		{
			text: '我的',
			icon: 'icon-user'
		}
	]
	const currentTab = ref(1) // 当前在发现页

	const switchTag = (index) => {
		currentTag.value = index
		currentPage.value = 1
		loadData()
	}
	// 列表数据
	const deviceList = ref([])
	const loading = ref(false)
	const refreshing = ref(false)
	const currentPage = ref(1)
	const pageSize = 10

	// 加载数据时保存原始列表
	const loadData = async () => {
		if (loading.value) return
		loading.value = true

		try {
			const res = await deviceStore.loadPublicDevices({
				current: currentPage.value,
				size: pageSize,
				category: currentTag.value === 0 ? '' : tags[currentTag.value]
			})

			if (res.code === 200) {
				const records = res.data.records || []
				if (currentPage.value === 1) {
					deviceList.value = records
					originalList.value = records // 保存原始数据
				} else {
					deviceList.value.push(...records)
					originalList.value.push(...records) // 保存原始数据
				}
			} else {
				throw new Error(res.message || '加载失败')
			}
		} catch (error) {
			console.error('加载失败:', error)
			uni.showToast({
				title: error.message || '加载失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
			refreshing.value = false
		}
	}

	// 其他方法保持不变...
	const loadMore = () => {
		currentPage.value++
		loadData()
	}

	const refresh = () => {
		refreshing.value = true
		currentPage.value = 1
		loadData()
	}

	const handleAdd = async (device) => {
	  try {
	    const res = await deviceStore.collectDevice(device.id)
	    if (res && res.code === 200) {
	      // 使用 uni.showToast 替代 message
	      uni.showToast({
	        title: '添加成功',
	        icon: 'success'
	      })
	      // 刷新列表
	      await loadData()
	    }
	  } catch (error) {
	    console.error('添加失败:', error)
	    uni.showToast({
	      title: error.message || '添加失败',
	      icon: 'none'
	    })
	  }
	}

	const formatNumber = (num) => {
		return ((num || 0) / 10000).toFixed(1)
	}

	// 切换标签页
	const switchTab = (index) => {
		const routes = [
			'/pages/index/index',
			'/pages/discover/discover',
			'/pages/create/create',
			'/pages/notification/notification',
			'/pages/my/my'
		]
		uni.switchTab({
			url: routes[index]
		})
	}

	onMounted(() => {
		loadData()
	})
</script>

<style lang="scss">
	.discover-container {
		min-height: 100vh;
		background: #f8f9fa;
		padding-bottom: calc(110rpx + env(safe-area-inset-bottom));

		// 顶部导航
		.nav-bar {
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			background: #fff;
			border-bottom: 1px solid #f5f5f5;

			.title {
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
			}
		}

		// 搜索框
		.search-box {
			padding: 24rpx 30rpx;
			background: #fff;

			.search-input-box {
				display: flex;
				align-items: center;
				background: #f5f6f7;
				border-radius: 36rpx;
				padding: 16rpx 24rpx;

				.icon-search {
					margin-right: 12rpx;
					font-size: 28rpx;
					color: #999;
				}

				.search-input {
					flex: 1;
					height: 40rpx;
					min-height: 40rpx;
					font-size: 28rpx;
					color: #333;
				}

				.search-placeholder {
					color: #999;
				}
			}
		}

		// 标签栏
		.tag-scroll {
			padding: 0 30rpx;
			white-space: nowrap;
			background: #fff;
			height: 88rpx;

			.tag-item {
				display: inline-block;
				padding: 24rpx 32rpx;
				margin-right: 24rpx;
				font-size: 28rpx;
				color: #666;
				position: relative;

				&.active {
					color: #007AFF;
					font-weight: 500;
				}

				&:last-child {
					margin-right: 0;
				}
			}
		}

		// banner区域
		.banner-box {
			margin: 24rpx 30rpx;
			border-radius: 20rpx;
			overflow: hidden;
			position: relative;
			background: #fff;

			.banner-img {
				width: 100%;
				height: 200rpx;
			}

			.banner-text {
				position: absolute;
				left: 30rpx;
				top: 30rpx;
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.banner-btn {
				position: absolute;
				left: 30rpx;
				bottom: 30rpx;
				background: rgba(255, 255, 255, 0.9);
				color: #007AFF;
				padding: 12rpx 32rpx;
				border-radius: 32rpx;
				font-size: 26rpx;
				font-weight: 500;
			}
		}

		// AI列表
		.device-list {
			padding: 0 30rpx;
			margin-bottom: 110rpx;

			.device-item {
				display: flex;
				align-items: flex-start;
				padding: 24rpx;
				background: #fff;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
				max-width: 660rpx;

				.avatar {
					width: 88rpx;
					height: 88rpx;
					border-radius: 44rpx;
					margin-right: 20rpx;
					background: #f5f6f7;
				}

				.content {
					flex: 1;
					min-width: 0;

					.title {
						font-size: 32rpx;
						font-weight: 600;
						color: #333;
						margin-bottom: 8rpx;
						line-height: 1.4;
					}

					.desc {
						font-size: 26rpx;
						color: #666;
						line-height: 1.5;
						margin-bottom: 12rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
					}

					.chat-info {
						display: flex;
						align-items: center;

						.chat-count {
							font-size: 24rpx;
							color: #999;
						}
					}
				}

				.add-btn {
					width: 56rpx;
					height: 56rpx;
					flex-shrink: 0;
					border-radius: 28rpx;
					background: #007AFF;
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 36rpx;
					margin-left: 20rpx;
					margin-top: 8rpx;
				}
			}
		}

		// 底部导航
		.tab-bar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 110rpx;
			background: #fff;
			display: flex;
			align-items: center;
			border-top: 1rpx solid #eee;
			padding-bottom: env(safe-area-inset-bottom);

			.tab-item {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #999;

				.iconfont {
					font-size: 48rpx;
					margin-bottom: 6rpx;
				}

				.text {
					font-size: 24rpx;
				}

				&.active {
					color: #007AFF;
				}
			}
		}
	}
</style>